package concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zyh
 * @Date:15:17 2018/2/2
 * @Description:
 */
public class Queue<T> {

    private Lock lock = new ReentrantLock();
    private Condition full = lock.newCondition();
    private Condition empty = lock.newCondition();
    private int count,addIndex,removeIndex;
    private Object[] items ;

    public Queue(int size){
        items = new Object[size];
    }
    private void add(T t) throws InterruptedException {
        lock.lock();

        try {
            while (count == items.length){
                full.await();
            }
            items[addIndex++] = t;
            count++;
            if(addIndex++ == items.length){
                addIndex = 0;
            }
            empty.signal();
        } finally {
            lock.unlock();
        }
    }
    private void remove(T t) throws InterruptedException {
        lock.lock();
        try {
            while(count == 0){
                empty.await();
            }
            count--;

        }finally {
            lock.unlock();
        }
    }
}
